package com.ibm.android.decode;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.os.Handler;
import android.os.Message;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.LuminanceSource;
import com.google.zxing.NotFoundException;
import com.google.zxing.ReaderException;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.ibm.android.R;

public class DecodeHandler extends Handler {
	private Handler mDecodeResultHandler;
	private int mPixelFormat;

	public DecodeHandler(Handler handler, int pixelFormat) {
		mDecodeResultHandler = handler;
		mPixelFormat = pixelFormat;
	}

	@Override
	public void handleMessage(Message message) {
		switch (message.what) {
		case R.id.decode:
			decode((byte[]) message.obj, message.arg1, message.arg2);
			break;
		}
	}

	/**
	 * Decode the data within the viewfinder rectangle, and time how long it
	 * took. For efficiency, reuse the same reader objects from one decode to
	 * the next.
	 * 
	 * @param data
	 *            The preview frame.
	 * @param width
	 *            The width of the preview frame.
	 * @param height
	 *            The height of the preview frame.
	 */
	private void decode(byte[] data, int width, int height) {
		LuminanceSource source = null;
		switch (mPixelFormat) {
		case PixelFormat.JPEG:
			Bitmap mBitmap = BitmapFactory
					.decodeByteArray(data, 0, data.length);
			source = new JPegLuminanceSource(mBitmap);
			break;
		}

		if (source == null) {
			Message message = mDecodeResultHandler
					.obtainMessage(R.id.decode_failed);
			message.sendToTarget();
			return;
		}

		// long start = System.currentTimeMillis();
		Result rawResult = null;
		BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
		try {
			QRCodeReader reader = new QRCodeReader();
			rawResult = reader.decode(bitmap);
			Message message = mDecodeResultHandler.obtainMessage(
					R.id.decode_succeeded, rawResult.getText());
			message.sendToTarget();
			return;
		} catch (NotFoundException ne) {
		} catch (ReaderException re) {
		}

		// If we get here, there was either no QR code found or an reader
		// exception.
		Message message = mDecodeResultHandler
				.obtainMessage(R.id.decode_failed);
		message.sendToTarget();
	}
}
